from flask import g, jsonify, render_template, current_app

from info import constants
from info.models import News, Comment
from info.utils.common import user_getter
from info.utils.response_code import RET
from . import news_blue


@news_blue.route('/<news_id>')
@user_getter
def detail(news_id):
    """
    文章详情页
    返回json数据,字典data包含
    is_collected 用户是否收藏
    news: 新闻的详情字典
    click_news_list: 热点新闻列表
    user: 用户的信息字典()
    """
    user = g.user
    news_model = None
    try:
        news_model = News.query.filter(News.id == news_id).first()
    except Exception as e:
        current_app.logger.error(e)
    if not news_model:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")

    news = news_model.to_dict()

    # 新闻评论
    comments_model, comments_list = None,[]
    try:
        comments_model = Comment.query.filter(Comment.news_id == news_id).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    for comments in comments_model:
        comments_list.append(comments.to_dict())

    click_news_list, rank_news_model = [], None
    try:
        rank_news_model = News.query.order_by(News.clicks.desc()).paginate(1, constants.CLICK_RANK_MAX_NEWS, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    for rank_news in rank_news_model.items:
        click_news_list.append(rank_news.to_basic_dict())

    data ={
        "user": user.to_dict() if user else None,
        "news":news,
        'comments': comments_list,
        "click_news_list":click_news_list
    }
    return render_template("news/detail.html", data = data)